const { Paragraph, TextRun } = require("docx");
const { getAlignment, getIndentValue, getPrefixSymbol, mapFontSizeToHalfPoints } = require("../common/utils");
const { formatDateTime } = require("../common/formatters");

const dateFormatMap = {
  'yyyy-mm-dd': '|___|___|___|___|年|___|___|月|___|___|日',
  'mm-dd': '|___|___|月|___|___|日',
  'yyyy-mm-dd hh:mm': '|___|___|___|___|年|___|___|月|___|___|日 |___|___|时|___|___|分',
  'yyyy-mm-dd hh:mm:ss': '|___|___|___|___|年|___|___|月|___|___|日 |___|___|时|___|___|分|___|___|秒',
  'hh:mm': '|___|___|时|___|___|分',
  'hh:mm:ss': '|___|___|时|___|___|分|___|___|秒',
};

function generateDateTimeGroup(field, baseIndent = 0) {
    const { value } = field;
    const finalIndent = getIndentValue(value?.alignment, baseIndent);
    const sizeHalfPoints = mapFontSizeToHalfPoints(value?.fontSize);
    const children = [];
    
    // 添加前缀符号
    if (value?.prefixSymbol && value.prefixSymbol !== 'none') {
        const symbol = getPrefixSymbol(value.prefixSymbol);
        if (symbol) {
            children.push(new TextRun({
                text: symbol,
                size: sizeHalfPoints,
                font: "SimSun" // 宋体
            }));
        }
    }
    
    // 添加字段名称
    if (value?.fieldName && value.fieldName.trim()) {
        children.push(new TextRun({
            text: value.fieldName,
            size: sizeHalfPoints,
            bold: value?.isBold || false,
            font: "SimSun"
        }));
    }
    
    // 根据格式生成日期时间字符串
    const dateStr = formatDateTimeByFormat(value);
    children.push(new TextRun({
        text: dateStr,
        size: sizeHalfPoints,
        font: "SimSun"
    }));
    
    // 添加后缀
    if (value?.suffix) {
        children.push(new TextRun({
            text: ' ' + value.suffix,
            size: sizeHalfPoints,
            font: "SimSun"
        }));
    }
    
    return [
        new Paragraph({
            indent: { left: finalIndent },
            alignment: getAlignment(value?.labelAlign || value?.alignment),
            spacing: { before: 100, after: 100, line: 360 },
            children
        })
    ];
}

// 根据格式格式化日期时间
function formatDateTimeByFormat(value) {
    if (!value || !value.dateFormat) {
        return '____-__-__ __:__:__'; // 默认回退格式
    }
    return dateFormatMap[value.dateFormat] || '____-__-__ __:__:__';
}

module.exports = {
    generateDateTimeGroup
}; 